#include "filelist.hpp"
#include "fs.hpp"
#include "common.hpp"

int FileList::rowCount(const QModelIndex &) const
{
	return files.size();
}

QVariant FileList::data(const QModelIndex &index, int role) const
{
	if(!index.isValid())
		return QVariant();
	if( role == Qt::DisplayRole ){
		FileInfo fi; 
		if(index.column() != name){
			fs->stat(getFilePath(index), &fi);
		}
		switch(index.column()){
		case name:
			return files[index.row()];
		case ctime:
			return fi.ctime;
		case mtime:
			return fi.mtime;
		case dtime:
			return fi.mtime;
		case size:
			return fi.size;
		case blocks:
			return fi.blocks;
		}
	}
	if( role == Qt::ToolTipRole )
		return getFilePath(index);
	return QVariant();
}

QString FileList::getFilePath( const QModelIndex& index ) const
{
	return path + QDir::separator() + files[index.row()];
}

static char *names[] = { "name", "size", "blocks", "ctime", "mtime", "dtime", };
QVariant FileList::headerData(int section, Qt::Orientation orientation, int role) const
{
	if (role != Qt::DisplayRole)
		return QVariant();

	if (orientation == Qt::Horizontal){
		return names[section];
	}

	return QVariant();
}

FileList::FileList(FS *argFs)
{
	fs = argFs;
}

void FileList::setPath(const QModelIndex& index)
{
	QModelIndex it = index;
	QStringList sl;
	while(it.isValid()){
		sl.prepend(it.model()->data(it, Qt::DisplayRole).toString());
		it = it.parent();
	}
	QString path = QDir::separator() + sl.join(QDir::separator());
	log("FileList: setPath '%s'\n", path.toLocal8Bit().data() );
	this->path = path;
	files = fs->entryList(path, QDir::Files);
	reset();
}
